import { login, logout, getInfo } from '@/api/system'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [], // 角色权限控制按钮显示
    menus: [] // 菜单权限
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles // 角色权限
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus // 菜单权限
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        console.log("login", response);
        
        const { data } = response
        commit('SET_TOKEN', data.data.token)
        setToken(data.data.token)
        resolve(response)
      }).catch(error => {
        // reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        if (response.data.code == 200) {
          if (!response) {
            return reject('Verification failed, please Login again.')
          }
          console.log("response.data", response.data);
          commit('SET_NAME', response.data.data.username)
          if (response.data.data.avatarPath != null) {
            commit('SET_AVATAR', response.data.data.avatarPath)
          } else {
            commit('SET_AVATAR', '')
          }
          // // commit('SET_ROLES', roles) // 角色权限
          if (response.data.data.permissionList != null) {
            commit('SET_MENUS', response.data.data.permissionList) // 菜单权限
          } else {
            commit('SET_MENUS', []) // 菜单权限
          }
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      logout().then((res) => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

